package com.lemon.system.controller;

import com.lemon.common.core.constant.CacheConstants;
import com.lemon.common.core.utils.StringUtils;
import com.lemon.common.core.web.controller.BaseController;
import com.lemon.common.core.web.domain.AjaxResult;
import com.lemon.common.core.web.page.TableDataInfo;
import com.lemon.common.log.annotation.Log;
import com.lemon.common.log.enums.BusinessType;
import com.lemon.common.redis.service.RedisService;
import com.lemon.common.security.annotation.RequiresPermissions;
import com.lemon.system.api.model.LoginUser;
import com.lemon.system.domain.SysUserOnline;
import com.lemon.system.service.ISysUserOnlineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * 在线用户监控
 * 
 * @author huangpeng
 */
@RestController
@RequestMapping("/online")
public class SysUserOnlineController extends BaseController
{
    @Autowired
    private ISysUserOnlineService userOnlineService;

    @Autowired
    private RedisService redisService;

    /**
     * 在线用户查询
     * @Title: list
     * @Description: 在线用户查询
     * @param ipaddr
     * @param userName
     * @param loginSystem
     * @return: TableDataInfo
     * @throws:
     * @author: huangpeng
     * @Date: 2024/1/6 18:22
     */
    @RequiresPermissions("monitor:online:list")
    @GetMapping("/list")
    public TableDataInfo list(String ipaddr, String userName, String loginSystem)
    {
        Collection<String> keys = redisService.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        List<SysUserOnline> userOnlineList = new ArrayList<SysUserOnline>();
        for (String key : keys)
        {
            SysUserOnline user = userOnlineService.loginUserToUserOnline(redisService.getCacheObject(key));
            if (StringUtils.isNotEmpty(loginSystem) && !StringUtils.equals(loginSystem, user.getLoginSystem())) {
                continue;
            }
            if (StringUtils.isNotEmpty(ipaddr) && !StringUtils.equals(ipaddr, user.getIpaddr())) {
                continue;
            }
            if (StringUtils.isNotEmpty(userName) && !StringUtils.equals(userName, user.getUserName())) {
                continue;
            }
            userOnlineList.add(user);
        }
        Collections.reverse(userOnlineList);
        userOnlineList.removeAll(Collections.singleton(null));
        return getDataTable(userOnlineList);
    }

    /**
     * 强退用户
     */
    @RequiresPermissions("monitor:online:forceLogout")
    @Log(title = "在线用户", businessType = BusinessType.FORCE)
    @DeleteMapping("/{tokenId}")
    public AjaxResult forceLogout(@PathVariable String tokenId)
    {
        redisService.deleteObject(CacheConstants.LOGIN_TOKEN_KEY + tokenId);
        return AjaxResult.success();
    }
}
